package com.shen.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SaleTicketDemo02 {
    public static void main(String[] args) {

        Ticket02 ticket=new Ticket02();
        //多个线程抢夺同一个资源
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"C").start();
        
    }
}

///资源类
class Ticket02{
    private int number =50;
    private int saleTicket=0;
    public  void sale(){
        Lock lock=new ReentrantLock();//new 一个锁

        lock.lock();//加锁

        try {
            if(number<=50&&saleTicket<50){
                number=number-1;
                saleTicket=saleTicket+1;
                System.out.println(Thread.currentThread().getName()+"卖出了第"+saleTicket+"票，剩余:"+number+"票");
            }else{
                System.out.println("票已卖完！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }

    }
}
